package com.example.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.example.common.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @date
 * @description 文件上传
 */
@RestController
@RequestMapping("/files")
@Slf4j
@Api(tags = "文件相关接口",value = "文件相关接口")
public class FileController {

    @Value("${files.basePath}")
    private String basePath;

    //basePath+date
    private String fullPath;

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        String date = this.createFolder();
        String flag = IdUtil.simpleUUID()+this.getFileExtension(file.getOriginalFilename());
        try {
            FileUtil.writeBytes(file.getBytes(), this.fullPath+ "/" + flag);
            log.info("[文件]: {} <上传成功>",this.fullPath + flag);
        } catch (Exception e) {
            log.info("[文件]: {} <上传失败>",this.fullPath + flag);
        }
        return Result.success(date+"_"+flag);
    }



    /**
     * 获取文件
     * @param flag date_uuid
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFile(@PathVariable String flag, HttpServletResponse response) {
        try {
            // 构建文件路径
            String filePath = this.basePath + "/" + flag.replace("_","/");
            File file = new File(filePath);
            if (file.exists()) {
                // 设置响应头
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(flag, "UTF-8"));
                // 将文件内容写入响应流
                try (OutputStream outputStream = response.getOutputStream()) {
                    Files.copy(file.toPath(), outputStream);
                    outputStream.flush();
                } catch (IOException e) {
                    log.error("[获取文件失败]: {}", filePath, e);
                }
            } else {
                log.info("[文件不存在]: {}", filePath);
                // 返回文件不存在的响应
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Exception e) {
            log.error("[获取文件异常]: {}", flag, e);
            // 返回异常的响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }


    private String createFolder() throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        File folder = new File(basePath, date);
        if (!folder.exists()) {
            if (folder.mkdirs()) {
                this.fullPath = folder.getAbsolutePath();
                log.info("[创建日期文件夹成功]: {}", fullPath);
            } else {
                log.info("[创建日期文件夹失败]: {}", folder.getAbsolutePath());
                throw new IOException();
            }
        } else {
            this.fullPath = basePath + "/" +date;
            log.info("[日期文件夹已存在]: {}", folder.getAbsolutePath());
        }
        return date;
    }

    // 辅助方法，用于从文件名中提取扩展名
    private String getFileExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex == -1) {
            return "";
        }
        return filename.substring(dotIndex);
    }
}
